package cn.topcodes.tcsf.admin.web.interceptor;

import cn.topcode.unicorn.utils.RenderUtil;
import cn.topcode.unicorn.utils.StringUtil;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.admin.service.licence.LicenceException;
import cn.topcodes.tcsf.admin.service.licence.LicenceService;
import cn.topcodes.tcsf.admin.service.ops.OpsConnectedListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Unicorn
 * @date 2017/5/9
 */
public class LicenceInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(LicenceInterceptor.class);

    @Autowired
    private LicenceService licenceSerivce;

    @Autowired
    private OpsConnectedListener opsConnectedListener;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        opsConnectedListener.setVersionFilePath(request.getServletContext().getRealPath("/") + "version.md");
        opsConnectedListener.setHttpPort(request.getServerPort());
        opsConnectedListener.setContextPath(request.getContextPath());

        try {
            licenceSerivce.validate();
            return super.preHandle(request, response, handler);
        }catch(LicenceException e) {
            String contentType = request.getHeader("accept");
            if(StringUtil.isBlank(contentType)|| contentType.contains(MediaType.TEXT_HTML_VALUE)) {
                response.sendRedirect(request.getContextPath() + "/licence");
            }else {
                RenderUtil.renderJson(ApiResponseEntity.buildFailed(e.getMessage()), response);
            }
            return false;
        }
    }
}
